<?php

/**
 * 角色
 *
 * @author dalei.chen
 */

require_once 'CommonController.php';

class Admin_RoleController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_Role();
        $this->view->title = "管理中心";
    }

    /**
     * 默认动作
     * 
     * @return void
     */
    public function indexAction()
    {   
        $partnerModel = new Application_Model_Partner();
        $menuModel = new Application_Model_Menu();
        $roleMenuModel = new Application_Model_RoleMenu();
        $time = time();

        //获取当前页码
        $pageSize = 20;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }

        //设置URL模板以及条件
        $urls = array();
        $vars = array();
        $wheres = array();

        $vars['name'] = trim($this->_request->get('name'));
        $vars['partnerName'] = trim($this->_request->get('partnerName'));
        $urls = $vars;

        if ($vars['name'] != '') {
            $wheres[] = "`r`.`name` LIKE '%" . addslashes($vars['name']) . "%'";
        }
        if ($vars['partnerName'] != '') {
            if (strpos($vars['partnerName'], '耶客') !== FALSE || strtolower($vars['partnerName']) == 'yek') {
                $wheres[] = "`r`.`type` = 1";
            } else {
                $wheres[] = "`p`.`name` LIKE '%" . addslashes($vars['partnerName']) . "%'";
            }
        }

        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $sql = "SELECT `r`.*, `p`.`name` AS `partnerName`
            FROM `{$this->_model->getTableName()}` AS `r` 
            LEFT JOIN `{$partnerModel->getTableName()}` AS `p` ON `r`.`partnerCode` = `p`.`code` 
            {$where} 
            ORDER BY `r`.`id` DESC
        ";

        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();

        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;
        
        $rows = $dbPaginator->getRows();

        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();
        $this->view->rows = $rows;
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
        $this->view->vars = $vars;
    }

    /**
     * 添加动作
     * 
     * @return void
     */
    public function insertAction()
    {
        $partnerModel = new Application_Model_Partner();
        $partnerRows = $partnerModel->fetchAll(NULL, "id desc");
        $this->view->partnerRows = $partnerRows;

        if ($this->_request->isPost()) {
            $field = array();
            $filter = new Zend_Filter_StripTags();
            $field['name'] = $filter->filter(trim($this->_request->getPost('name')));
            $field['type'] = $filter->filter(trim($this->_request->getPost('type')));
            $field['partnerCode'] = $field['type'] == 2 ? $filter->filter(trim($this->_request->getPost('partnerCode'))) : '';
            $field['notes'] = $filter->filter(trim($this->_request->getPost('notes')));
            $field['addTime']= date('Y-m-d H:i:s');
            $field['addUserName'] = Application_Model_UserLogin::getInstance()->getLoginedUserName();
            if (strlen($field['name']) > 50) {
                echo $this->view->message('名称长度必须小于50个字符，请重新填写！') ;
                exit;
            }
            if (strlen($field['name']) < 1) {
                echo $this->view->message('名称不能为空，请重新填写。') ;
                exit;
            }
            if ($field['type'] == 2 && empty($field['partnerCode'])) {
                echo $this->view->message('请选择一个公司，请重新填写。') ;
                exit;
            }
            if ($this->_model->isExists($field['name'], $field['type'], $field['partnerCode'])) {
                echo $this->view->message('你添加的角色已经存在。') ;
                exit;
            }
            $roleId = $this->_model->insert($field);
            echo $this->view->message('操作成功。', $this->view->projectUrl(array('action' =>'menu-set', 'id'=>$roleId))) ;
            exit;
        }
    }

    /**
     * 更新动作
     * 
     * @return void
     */
    public function updateAction()
    {
        $partnerModel = new Application_Model_Partner();
        $roleMenuModel = new Application_Model_RoleMenu();

        $id = intval($this->_request->get('id'));
        if (empty($id)) {
             exit("没有传递参数ID");
        }
        $row = $this->_model->fetchRow("`id` = {$id}"); 
        if (empty($row)) {
             exit("没有找到记录。");
        }
        
        //获取所有商家信息
        $partnerRows = $partnerModel->fetchAll(NULL, "id desc");

        $this->view->partnerRows = $partnerRows;
        $this->view->row = $row;

        if ($this->_request->isPost()) {
            $field = array();
            $filter = new Zend_Filter_StripTags();
            $field['name'] = $filter->filter(trim($this->_request->getPost('name')));
            $field['type'] = $filter->filter(trim($this->_request->getPost('type')));
            $field['partnerCode'] = $field['type'] == 2 ? $filter->filter(trim($this->_request->getPost('partnerCode'))) : '';
            $field['notes'] = $filter->filter(trim($this->_request->getPost('notes')));
            if (strlen($field['name']) > 50) {
                echo $this->view->message('名称长度必须小于50个字符，请重新填写！') ;
                exit;
            }
            if (strlen($field['name']) < 1) {
                echo $this->view->message('名称不能为空，请重新填写。') ;
                exit;
            }
            if ($field['type'] == 2 && empty($field['partnerCode'])) {
                echo $this->view->message('请选择一个公司，请重新填写。') ;
                exit;
            }
            if ($this->_model->isExists($field['name'], $field['type'], $field['partnerCode'], $row['id'])) {
                echo $this->view->message('你添加的角色已经存在。') ;
                exit;
            }
            $this->_model->update($field, "`id` = {$id}");
            //商家改变后，删除类型为商家的所有角色菜单
            if (($field['type'] == 2 && $field['type'] != $row['type']) && $field['partnerCode'] != $row['partnerCode']) {
                $roleMenuModel->delete("`roleId` = {$id}");
            }
            //类型改变后，删除所有角色菜单
            if ($field['type'] != $row['type']) {
                $roleMenuModel->delete("`roleId` = {$id}");
            }

            $backUrl = $this->_request->get('backUrl') != NULL ? urldecode($this->_request->get('backUrl')) : @$_SERVER['HTTP_REFERER'];
            echo $this->view->message("操作成功。", $backUrl) ;
            exit;
        }
    }

    /**
     * 删除动作
     * 
     * @return void
     */
    public function deleteAction()
    {
        if ($this->_request->isPost()) {
            $ids= $this->_request->getPost('selectId');
            
            if (is_array($ids)) {
                $this->_model->deleteByIds($ids);
            }
        }
        $backUrl = urldecode($this->_request->get('backUrl'));
        redirect($backUrl);
    }

    /**
     * 角色菜单设置
     * 
     * @return void
     */
    public function menuSetAction()
    {
        $partnerModel = new Application_Model_Partner();
        $roleMenuModel = new Application_Model_RoleMenu();
        $partnerProductModel = new Application_Model_PartnerProduct();
        $productMenuModel = new Application_Model_ProductMenu();

        $id = intval($this->_request->get('id'));
        if (empty($id)) {
             exit("没有传递参数ID");
        }
        $row = $this->_model->fetchRow("`id` = {$id}"); 
        if (empty($row)) {
             exit("没有找到记录。");
        }

        //YEK用户可以设置所有商家的所有产品菜单以及非产品菜单
        if ($row['type'] == 1) {
            $productRows = $partnerProductModel->getAdapter()->fetchAll("
                SELECT `product`.*, `partner`.`name` AS `partnerName` FROM `{$partnerProductModel->getTableName()}` AS `product`
                LEFT JOIN `{$partnerModel->getTableName()}` AS `partner` ON `product`.`partnerCode` = `partner`.`code`
                ORDER BY `partner`.`code` ASC, `product`.`id` ASC
            ");
        } else {
            //商家只能看到自己的产品菜单
            $productRows = $partnerProductModel->getAdapter()->fetchAll("
                SELECT `product`.*, `partner`.`name` AS `partnerName` FROM `{$partnerProductModel->getTableName()}` AS `product`
                LEFT JOIN `{$partnerModel->getTableName()}` AS `partner` ON `product`.`partnerCode` = `partner`.`code`
                WHERE `product`.`partnerCode` = '{$row['partnerCode']}'
                ORDER BY `partner`.`code` ASC, `product`.`id` ASC
            ");
        }

        $this->view->productRows = $productRows;
        $this->view->row = $row;
    }

    /**
     * 获取菜单html
     * 
     * @return void
     */
    public function menuHtmlAction()
    {
        $roleId = intval($this->_request->get('roleId'));
        $menuType = trim($this->_request->get('menuType'));

        $menuModel = new Application_Model_Menu();
        $partnerProductModel = new Application_Model_PartnerProduct();
        $productMenuModel = new Application_Model_ProductMenu();
        $roleMenuModel = new Application_Model_RoleMenu();
        $roleModel = new Application_Model_Role();

        //检查角色是否存在
        $roleRow = $roleModel->fetchRow("`id` = {$roleId}");
        if (empty($roleRow)) {
            exit('角色参数没有传递。');
        }

        $templateContent = file_get_contents(APPLICATION_PATH . '/configs/roleMenuTemplate.php');
        $this->view->roleId = $roleId;
        $this->view->menuType = $menuType;

        if ($roleRow['type'] == 1) {
            //类型为YEK
            if ($menuType == 2) {
                //查找非产品菜单，即一些公共菜单，例如用户管理...
                $where = "`status` = '1' AND `type` = '2'";

                //获取所有角色拥有的菜单ID，以便在产品菜单中进行是否授权校验
                $roleMenuRows = $roleMenuModel->fetchAll("`roleId` = {$roleId} AND `menuId` IN (SELECT `id` FROM `{$menuModel->getTableName()}` WHERE `type` = '2')");
                $roleMenuIds = array();
                foreach($roleMenuRows as $row) {
                    $roleMenuIds[] = $row['menuId'];
                }
            } else {
                //获取所有角色拥有的菜单ID，以便在产品菜单中进行是否授权校验
                $roleMenuRows = $roleMenuModel->fetchAll("`roleId` = {$roleId}");
                $roleMenuIds = array();
                foreach($roleMenuRows as $row) {
                    $roleMenuIds[] = $row['menuId'];
                }

                //查找产品菜单，跟商家的一样
                $where = "`status` = '1' AND `type` = '1' ";
                
            }
        } else {
            //获取所有角色拥有的菜单ID，以便在产品菜单中进行是否授权校验
            $roleMenuRows = $roleMenuModel->fetchAll("`roleId` = {$roleId}");
            $roleMenuIds = array();
            foreach($roleMenuRows as $row) {
                $roleMenuIds[] = $row['menuId'];
            }
            //类型为商家
            $where = "`status` = '1' AND `type` = '1'";
        }
        $currentData = array('roleMenuIds'=>$roleMenuIds);
        $this->view->listContent = $menuModel->makeChildrenListString(0, $templateContent, $currentData, $where);
    }

    /**
     * 保存菜单
     * 
     * @return void
     */
    public function menuSaveAction()
    {
        $roleId = intval($this->_request->get('roleId'));
        $menuType = trim($this->_request->get('menuType'));
        $menuIds = trim($this->_request->get('menuIds')) != NULL ? explode(',', trim($this->_request->get('menuIds'))) : array();

        $menuModel = new Application_Model_Menu();
        $partnerProductModel = new Application_Model_PartnerProduct();
        $productMenuModel = new Application_Model_ProductMenu();
        $roleMenuModel = new Application_Model_RoleMenu();
        $roleModel = new Application_Model_Role();

        //检查角色是否存在
        $roleRow = $roleModel->fetchRow("`id` = {$roleId}");
        if (empty($roleRow)) {
            exit(Zend_Json::encode(array('status'=>1, 'message'=>'角色参数没有传递。')));
        }

        $where = '';
        //如果是YEK非产品菜单，即一些公共菜单，例如用户管理...
        if ($roleRow['type'] == 1 && $menuType == 2) {
            $where = "`roleId` = {$roleId} AND `menuId` IN (SELECT `id` FROM `{$menuModel->getTableName()}` WHERE `type` = '2')";
            $roleMenuRows = $roleMenuModel->fetchAll($where);
            $existsMenuIds = array();
            foreach($roleMenuRows as $row) {
                $existsMenuIds[] = $row['menuId'];
            }
        } else {
            $where = "`roleId` = {$roleId} AND `menuId` IN (SELECT `id` FROM `{$menuModel->getTableName()}` WHERE `type` = '1')";
            $roleMenuRows = $roleMenuModel->fetchAll($where);
            $existsMenuIds = array();
            foreach($roleMenuRows as $row) {
                $existsMenuIds[] = $row['menuId'];
            }
        }

        //删除已不存在的，添加不存在的
        $deleteMenuIds = array_diff($existsMenuIds, $menuIds);
        $insertMenuIds = array_diff($menuIds, $existsMenuIds);

        if (count($deleteMenuIds) > 0) {
            $roleMenuModel->delete("`menuId` IN (". implode(',', $deleteMenuIds) .") AND {$where}");
        }

        if (count($insertMenuIds) > 0) {
            foreach($insertMenuIds as $menuId) {
                $roleMenuModel->insert(array('roleId'=>$roleId, 'menuId'=>$menuId));
            }
        }
        exit(Zend_Json::encode(array('status'=>0, 'message'=>'保存成功。')));
    }

    /**
     * 返回JSON角色包含的用户
     * 
     * @return void
     */
    public function getRoleUserJsonAction()
    {
        $roleId = intval($this->_request->get('roleId'));

        $userModel = new Application_Model_User();
        $userRoleModel = new Application_Model_UserRole();

        $sql = "SELECT * FROM `{$userModel->getTableName()}` WHERE `id` IN (
                    SELECT `userId` FROM `{$userRoleModel->getTableName()}` WHERE `roleId` = {$roleId}
                )
                ORDER BY `addTime` DESC
        ";
        $this->view->userRows = $userModel->getAdapter()->fetchAll($sql);
    }

}